<?php
// +----------------------------------------------------------------------
// | SparkERP 优秀的进销存系统
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2099 http://erp.sparkshop.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai  <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\service\data;

use app\model\data\BrandCate;
use app\validate\data\BrandCateValidate;
use think\db\exception\DbException;
use think\exception\ValidateException;

class BrandCateService
{
    private BrandCate $brandCateModel;

    public function __construct(BrandCate $brandCateModel)
    {
        $this->brandCateModel = $brandCateModel;
    }

    /**
     * 获取品牌分类列表
     * @param array $param
     * @return array
     * @throws DbException
     */
    public function getList(array $param): array
    {
        $limit = $param['limit'];
        $name = $param['name'] ?? '';

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $list = $this->brandCateModel->where($where)->order('sort desc')->paginate($limit);

        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加品牌分类
     * @param array $param
     * @return array
     */
    public function addBrandCate(array $param): array
    {
        // 检验完整性
        try {
            validate(BrandCateValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }

        $has = $this->brandCateModel->checkUnique([
            'name' => $param['name']
        ])['data'];

        if (!empty($has)) {
            return dataReturn(-2, '该品牌分类已经存在');
        }

        $param['create_time'] = now();
        return $this->brandCateModel->insertOne($param);
    }

    /**
     * 编辑品牌分类
     * @param array $param
     * @return array
     */
    public function editBrandCate(array $param): array
    {
        // 检验完整性
        try {
            validate(BrandCateValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $this->brandCateModel->checkUnique($where)['data'];

        if (!empty($has)) {
            return dataReturn(-2, '该品牌分类已经存在');
        }

        $param['update_time'] = date('Y-m-d H:i:s');
        return $this->brandCateModel->updateById($param, $param['id']);
    }

    /**
     * 删除品牌分类
     * @param int $id
     * @return array
     */
    public function delBrandCate(int $id): array
    {
        return $this->brandCateModel->delById($id);
    }
}